package main

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/config"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/plugins/cors"
	_ "github.com/go-sql-driver/mysql"
	"shop/models/sadmin"
	_ "shop/routers"
)

func init()  {
	orm.RegisterDriver("mysql",orm.DRMySQL)
	st,_:=config.NewConfig("ini","conf/app.conf")
	datasource:=st.String("sqlconn")
	orm.RegisterDataBase("default", "mysql", datasource,30,30)
	orm.RunSyncdb("default",false,true)
}
func main() {
	if beego.BConfig.RunMode == "dev" {
		beego.BConfig.WebConfig.DirectoryIndex = true
		beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
	}
	//acao
	beego.InsertFilter("*",beego.BeforeRouter,cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
	}))
	//typefilter
	var FilterType = func(ctx *context.Context) {
		t := ctx.Input.Header("Authorization")
		if er:=sadmin.Checkrole(t);er!=nil{
			ctx.ResponseWriter.WriteHeader(201)
			ctx.WriteString("have no access")
		}
	}

	var FilterType2= func(ctx *context.Context) {
		t := ctx.Input.Header("Authorization")
		if er:=sadmin.Checkrole2(t);er!=nil{
			ctx.ResponseWriter.WriteHeader(201)
			ctx.WriteString("have no access")
		}
	}

	beego.InsertFilter("/v1/type/type/*",beego.BeforeExec,FilterType)
	//companyfilter
	beego.InsertFilter("/v1/company/*",beego.BeforeExec,FilterType2)
	//faqfilter
	beego.InsertFilter("/v1/faq/faq/*",beego.BeforeExec,FilterType)
	//usfilter
	beego.InsertFilter("/v1/us/us/*",beego.BeforeExec,FilterType)
	//appfilter

	st,_:=config.NewConfig("ini","conf/app.conf")
	filename:=st.String("fileurl")
	beego.SetStaticPath(filename,filename)
	beego.Run()
}
